//  添加\删除蒙版
Vue.prototype.mask = function (str,funOne,funTwo){
  if(str>0){
    var mask = document.createElement('div');
    mask.className = 'mask';
    document.body.appendChild(mask);
  }else if(str<0){
    var mask = document.querySelector('.mask')
    document.body.removeChild(mask);
  }
}
//上拉加载
function refresh(callback) {
  var container = document.querySelector('#container');
  var conText = document.createElement('div');
  conText.className = 'refresh-tips';
  conText.innerHTML = '上拉加载更多数据';
  setTimeout(function(){
    container.appendChild(conText);
  },10)
  window.addEventListener("scroll",function(){
    var winHeight = document.documentElement.clientHeight;
    var docHeight = document.body.clientHeight;
    var docOffTop = document.body.scrollTop;
    if(docOffTop == docHeight-winHeight){
      refreshText('正在加载....')
      callback();
    }
  })
}
//加载时文字显示
function refreshText(bingo){
  var refreshTips = document.querySelector('.refresh-tips');
  refreshTips.innerHTML = bingo;
}
//弱提示
function toast(tipText,timer){
  timer?timer:timer = 3000;
	//创建虚拟DOM
	var toastDom = document.createElement('div');
  toastDom.className = 'msg-toast';
	toastDom.innerHTML = tipText;
	document.body.appendChild(toastDom);
  var thisToast = document.querySelectorAll('.msg-toast');
  //toastDom[0].style.cssText = 'color:red';
  for(var i=0;i<thisToast.length;i++){
    thisToast[i].style.cssText = 'margin-left:-'+thisToast[i].scrollWidth/2+'px;'
  }
	//关闭程序
	setTimeout(function(){
		document.body.removeChild(toastDom)
	},timer)
}
//加载提示
loader = {
  init:function(loaderText){
    if(!loaderText) loaderText = '数据加载中';
    var loader = "<div class='loader'><div class='spinner'><i></i></div>"+loaderText+"</div>"
    var loaderWrap = document.createElement('div');
    loaderWrap.className = 'loader-wrap';
    loaderWrap.innerHTML = loader;
    document.body.appendChild(loaderWrap);
  },
  remove:function(){
    document.body.removeChild(document.querySelector('.loader-wrap')) //关闭程序
  }
}

//全局过滤器
Vue.filter('formatNum',function(str,front,back){
  if(!isNaN(str)){ var str =str.toFixed(2) }
  if(str == null || !str) return '-'
  return front+str+back;
})
//时间处理
Vue.filter('formatTime',function(timeStamp,type){
	//timeStamp是整数，否则要parseInt转换
	var time = new Date(timeStamp);
	var year = time.getFullYear();
	var month = time.getMonth()+1;
	var day = time.getDate();
	var hours = time.getHours();
	var minutes = time.getMinutes();
	var second = time.getSeconds();
  if(type == 'more'){
    return [year,month,day].map(addFrontZero).join('-')+' '+[hours,minutes,second].map(addFrontZero).join(':');
  }else if(type == 'more2'){
    return [hours,minutes].join(':')+' '+[year,month,day].map(addFrontZero).join('-');
  }else if(type == 'more3'){
    return [year,month,day].map(addFrontZero).join('-')+' '+[hours,minutes].map(addFrontZero).join(':');
  }else if(type == 'more4'){
    return [year,''].map(addFrontZero).join(' / ')+[month,day].map(addFrontZero).join('.')
  }else if(!type){
  	return [year,month,day].map(addFrontZero).join('-')
  }
})
function formatTime(timeStamp,type){
  //timeStamp是整数，否则要parseInt转换
  var time = new Date(timeStamp);
  var year = time.getFullYear();
  var month = time.getMonth()+1;
  var day = time.getDate();
  var hours = time.getHours();
  var minutes = time.getMinutes();
  var second = time.getSeconds();
  if(type == 'more'){
    return [year,month,day].map(addFrontZero).join('-')+' '+[hours,minutes,second].map(addFrontZero).join(':');
  }else if(!type){
    return [year,month,day].map(addFrontZero).join('-')
  }
}
// 时间列表
function timeStampListConvert(jsonDateList) {
  var dateArray = new Array();
  if (!jsonDateList) {
    return dateArray;
  }
  for(var vIndex in jsonDateList){ 
       dateArray.push(formatTime(jsonDateList[vIndex])); 
    }
    return dateArray;
}

function addFrontZero(str){
  if(!str) return '';
  var str = str.toString();
  return str[1]?str:'0'+str;
}
//vue-resorce方法封装
//验证的GET请求
function get(url,params,callback,errorHandler){
  baseGet(url,params,callback,errorHandler);
}

function noParamsGet(url,callback,errorHandler){
  baseGet(url,{},callback,errorHandler);
}

//验证的POST请求
function post(url, params,callback,errorHandler){
  basePost(url,params,callback,errorHandler)
}

function noParamsPost(url,callback,errorHandler){
  basePost(url,{},callback,errorHandler)
}

function customAuthPost(url, params, callback, notLogin, errorHandler) {
  var authToken = window.localStorage.getItem(siteTokenKey);
  basePost(url, params, authToken, callback, notLogin, errorHandler);
}

function baseGet(path,parameters,callback,errorHandler){
  var authToken = window.localStorage.getItem(siteTokenKey);
  if (!authToken) {
     authToken="";
  }
  Vue.http.get(
    siteDomain + path,
    {headers:{"X-Auth-Token":authToken}, params: parameters, emulateJSON:true}
  ).then(function(res){
     handleResponse(res, callback, errorHandler);
  }, function(res){
    if (res.data && res.data.code=='NOT_LOGIN') {
      window.localStorage.removeItem(siteTokenKey);
    }
    toast('请求异常，请联系客服')
    loader.remove();
  });
}

function basePost(path,parameters,callback,errorHandler){
  var authToken = window.localStorage.getItem(siteTokenKey);
  if (!authToken) {
     authToken="";
  }
  Vue.http.post(
    siteDomain + path,
    parameters,
    {headers:{"X-Auth-Token":authToken}, emulateJSON:true}
  ).then(function(res){
    handleResponse(res, callback, errorHandler);
  }, function(res){
    if (res.data && res.data.code=='NOT_LOGIN') {
      window.localStorage.removeItem(siteTokenKey);
    }
    toast('请求异常，请联系客服');
    loader.remove();
  });
}

function upload(path, key, file, callback, errorHandler) {
   var authToken = window.localStorage.getItem(siteTokenKey);
  if (!authToken) {
     authToken="";
  }
  var formData = new FormData();
  formData.append(key, file);
  Vue.http.post(
    siteDomain + path,
    formData,
    {headers:{"X-Auth-Token":authToken, "Content-Type":"multipart/form-data"}}
  ).then(function(res){
    handleResponse(res, callback, errorHandler);
  }, function(res){
    toast('请求异常，请联系客服');
    loader.remove();
  });
}

//'Content-Type': 'application/json'
function handleResponse(response, callback, errorHandler) {
  if (response.data.code=='NOT_LOGIN') {
      window.localStorage.removeItem(siteTokenKey);
      if (errorHandler) {
        errorHandler(response.data);
      }else{
        toast('未登录');
        loader.remove();
      }
      return ;
  }
  if(response.data.code == "OK"){
    callback(response.data);
  } else if (errorHandler) {
    errorHandler(response.data);
  } else {
    toast(response.data.error);
    loader.remove();
  }
}

//银行卡号每四位加一个空格
function fomatBank(num) {
  var bankId=num.replace(/\s/g,'').replace(/(\d{4})(?=\d)/g,"$1 ");
  return bankId;
}
// 取消银行卡号空格
function delHtmlTag(str){
  var str=str.replace(/<\/?[^>]*>/gim,"");//去掉所有的html标记
  var result=str.replace(/(^\s+)|(\s+$)/g,"");//去掉前后空格
  return  result.replace(/\s/g,"");//去除文章中间空格
}

//身份证号验证
var aCity={11:"北京",12:"天津",13:"河北",14:"山西",15:"内蒙古",21:"辽宁",22:"吉林",23:"黑龙江",31:"上海",32:"江苏",33:"浙江",34:"安徽",35:"福建",36:"江西",37:"山东",41:"河南",42:"湖北",43:"湖南",44:"广东",45:"广西",46:"海南",50:"重庆",51:"四川",52:"贵州",53:"云南",54:"西藏",61:"陕西",62:"甘肃",63:"青海",64:"宁夏",65:"新疆",71:"台湾",81:"香港",82:"澳门",91:"国外"} 
function isCardID(sId){
  var iSum=0 ;
  var info="" ;
  if(!/^\d{17}(\d|x)$/i.test(sId)) return "你输入的身份证长度或格式错误";
  sId=sId.replace(/x$/i,"a");
  if(aCity[parseInt(sId.substr(0,2))]==null) return "你的身份证地区非法";
  sBirthday=sId.substr(6,4)+"-"+Number(sId.substr(10,2))+"-"+Number(sId.substr(12,2));
  var d=new Date(sBirthday.replace(/-/g,"/")) ;
  if(sBirthday!=(d.getFullYear()+"-"+ (d.getMonth()+1) + "-" + d.getDate()))return "身份证上的出生日期非法";
  for(var i = 17;i>=0;i --) iSum += (Math.pow(2,i) % 11) * parseInt(sId.charAt(17 - i),11) ;
  if(iSum%11!=1) return "你输入的身份证号非法";
  //aCity[parseInt(sId.substr(0,2))]+","+sBirthday+","+(sId.substr(16,1)%2?"男":"女");//此次还可以判断出输入的身份证号的人性别
  return 'true';
}

// 登录密码必须由6-18位字母与数字组成
function fomatPass(password) {
  var password=/^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{6,18}$/.test(password)
  return password;
}

//金额数字分割(每三位加一个逗号)
Vue.filter('formatThree',function(strNum){
  if (strNum.length <= 3) {
  return strNum;
  }
  if (!/^(\+|-)?(\d+)(\.\d+)?$/.test(strNum)) {
    return strNum;
  }
  var a = RegExp.$1, b = RegExp.$2, c = RegExp.$3;
  var re = new RegExp();
  re.compile("(\\d)(\\d{3})(,|$)");
  while (re.test(b)) {
    b = b.replace(re, "$1,$2$3");
  }
  return a + "" + b + "" + c;
})

// 检测是否登录 
function isLogin(){
  return window.localStorage.getItem(siteTokenKey)? true:false;
}


Vue.filter('formatBooleanType',function (boo) {
  if( boo  == true){
    return '是';
  }
  else{
    return '否';
  }
});


Vue.filter('percentAge',function(strNum){
  var rate=strNum*1;
  return rate.toFixed(4);
});

function getParameter(name){                        //获取链接参数
  var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)");
  var r = window.location.search.substr(1).match(reg);
  if(r!=null)return  unescape(r[2]); return null;
};

// 邮箱验证
function check( email_address ){
    var regex = /^([0-9A-Za-z\-_\.]+)@([0-9a-z]+\.[a-z]{2,3}(\.[a-z]{2})?)$/g;
    if ( regex.test( email_address ) ){
        var user_name = email_address.replace( regex, "$1" );
        var domain_name = email_address.replace( regex, "$2" );
        var alert_string = "您输入的电子邮件地址合法\n\n";
        alert_string += "用户名：" + user_name + "\n";
        alert_string += "域名：" + domain_name;
        // window.toast( alert_string );
        return true;
    }
    else{
        window.toast( "您输入的电子邮件地址不合法" );
        return false;
    }
}